package com.onpositive.datamap.core.impl;

import java.text.NumberFormat;
import java.text.ParseException;

import com.onpositive.data.IPropertyConstants;
import com.onpositive.data.IPropertyMetadata;
import com.onpositive.data.diskstorage.AbstractValueAccessor;
import com.onpositive.data.units.Unit;
import com.onpositive.data.units.Units;
import com.onpositive.datamap.IDataPropertyValue;
import com.onpositive.datamap.core.IDataProperty;
import com.onpositive.datamap.core.IDimensionProperty;
import com.onpositive.datamap.values.impl.DimensionRange;
import com.onpositive.datamap.values.impl.ScalarRange;

public class DimensionProperty extends ScalarProperty implements
		IDimensionProperty {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Unit unitByShortName;

	public DimensionProperty(IPropertyMetadata meta,
			AbstractValueAccessor collection) {
		super(meta, collection);
	}

	@Override
	public IDataPropertyValue convert(Object value) {
		if (value instanceof Double) {
			return new DimensionRange(this, null,
					((Double) value).doubleValue());
		}
		return (IDataPropertyValue) value;
	}

	@Override
	public Unit getPrimaryUnit() {
		if (unitByShortName != null) {
			return unitByShortName;
		}
		unitByShortName = Units
				.getUnitByShortName(
						(String) meta
								.getMetaPropertyValue(IPropertyConstants.CHAR_UNIT_LABEL),
						(String) meta
								.getMetaPropertyValue(IPropertyConstants.CHAR_UNIT_KIND_LABEL));
		return unitByShortName;
	}

	@Override
	public String simpleType() {
		return IPropertyConstants.PROP_KIND_DIMENSION;
	}

	@Override
	public Object parse(String c) {
		c = c.trim();
		if (c.length()==0){
			return null;
		}
		Unit unitByShortName = null;
		for (int a = c.length() - 1; a > 0; a--) {
			char charAt = c.charAt(a);
			if (Character.isDigit(charAt) || Character.isWhitespace(charAt)) {
				break;
			}
			unitByShortName = Units.getUnitByShortName(c.substring(a,
					c.length()), getPrimaryUnit().getKind().name());
		}
		int indexOf = c.indexOf(' ');

		String substring = indexOf > 0 ? c.substring(0, indexOf) : c;

		try {
			double doubleValue = ((Number) NumberFormat.getInstance()
					.parseObject(substring)).doubleValue();
			if (unitByShortName != null) {
				doubleValue = doubleValue
						* unitByShortName.getRelationToPrimary();
			}
			return doubleValue;
		} catch (ParseException e) {
			
		}
		return c;
	}

	@Override
	public ScalarRange newValue(double low, double high, Object comment) {
		return new DimensionRange(this, comment, low, high);
	}

	@Override
	public IDataProperty clone(AbstractValueAccessor va) {
		return new DimensionProperty(meta, va);
	}
}
